package com.zto.tbschedule.console.filter;

import com.alibaba.fastjson.JSON;
import com.zto.tbschedule.console.help.LoginHelp;
import com.zto.tbschedule.console.vo.Message;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component("loginFilter")
public class LoginFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = ((HttpServletRequest)servletRequest);
        if(LoginHelp.ignored(request.getServletPath())){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            if (LoginHelp.getUser(request) != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.getWriter().write(JSON.toJSONString(new Message<Void>(Message.LOGIN_TIMEOUT, "LOGIN_TIMEOUT", false)));
            }
        }
    }

    public void destroy() {

    }

}
